#include "StdAfx.h"
#include "Texture.h"

#include "sys/File.h"
#include "TexMgr.h"

typedef struct  
{
	u16	signature;		//should be 0x5854
	u16	palSize;		//how many colors are in the palette
	u16	tex_repeat:2;
	u16	tex_flip:2;
	u16	tex_sizeS:3;
	u16	tex_sizeT:3;
	u16	tex_format:3;
	u16	tex_use0:1;
	u16	tex_coord:2;
}TTexHeader;

CTexture::CTexture()
{
	
}

CTexture::~CTexture()
{
	
}

CTexture* CTexture::load(CFile *file)
{
	TTexHeader header;
	
	file->read(&header, sizeof(header));
	
	if (header.signature != 0x5854)
		return NULL; //invalid file
		
	CTexture *tex = new CTexture();
			
	tex->m_texFmt = (GXTexFmt)header.tex_format;
	tex->m_texGen = (GXTexGen)header.tex_coord;
	tex->m_texS = (GXTexSizeS)header.tex_sizeS;
	tex->m_texT = (GXTexSizeT)header.tex_sizeT;
	tex->m_texRepeat = (GXTexRepeat)header.tex_repeat;
	tex->m_texFlip = (GXTexFlip)header.tex_flip;
	tex->m_texPltt0 = (GXTexPlttColor0)header.tex_use0;
	 
    int szx = 8;
    int szy = 8;
    for (int i=0;i<8;i++)
    {
    	if (i<tex->m_texS)
    		szx *= 2;
    	if (i<tex->m_texT)
    		szy *= 2;
    }
    
    int ppb = 1; //pixels per byte
    if (tex->m_texFmt == GX_TEXFMT_PLTT4)
    	ppb = 4;
    if (tex->m_texFmt == GX_TEXFMT_PLTT16)
    	ppb = 2;
    
    tex->m_texSize = szx * szy / ppb;
    tex->m_palSize = header.palSize * 2;
    
	CTexMgr *mgr = CTexMgr::getInstance();
	
	if (
		(!mgr->allocTex(&tex->m_texAddr, &tex->m_texBank, tex->m_texSize)) ||
		(!mgr->allocPal(&tex->m_palAddr, &tex->m_palBank, tex->m_palSize))
	)
	{
		delete tex;
		return NULL;
	}
	
    tex->m_texAddr = 0x1000; //TODO
    tex->m_palAddr = 0x1000;
    
    
    tex->m_texData = new char[tex->m_texSize];
    tex->m_palData = new char[tex->m_palSize];
    
    file->read(tex->m_palData, tex->m_palSize);
    file->read(tex->m_texData, tex->m_texSize);
    
    return tex;
}

void CTexture::build3D()
{
	GX_BeginLoadTex();
	GX_LoadTex(m_texData, m_texAddr, m_texSize);
	GX_EndLoadTex();

	GX_BeginLoadTexPltt();
	GX_LoadTexPltt(m_palData, m_palAddr, m_palSize);
	GX_EndLoadTexPltt();
}

void CTexture::release3D()
{
	
}

void CTexture::use()
{
	G3_TexImageParam(m_texFmt,m_texGen,m_texS,m_texT,m_texRepeat,m_texFlip,m_texPltt0,m_texAddr);
	G3_TexPlttBase(m_palAddr, m_texFmt);
}
